package v2

import (
	"fmt"
	"ginblog/middeware"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/golang-jwt/jwt/v5"
	"net/http"
	"time"
)

// 前后端不分离登录验证
func Login(ctx *gin.Context) {
	var user model.User

	if ctx.Request.Method == "POST" {
		err := ctx.ShouldBindWith(&user, binding.Form)
		if err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			fmt.Println(err)
			return
		}
		var code int
		user, code = model.CheckLogin(user.Username, user.Password)
		if code == errmsg.SUCCESS {
			token, err := CreateToken(ctx, user)
			if err != nil {
				//返回错误页面
				fmt.Println(err)
				ctx.HTML(http.StatusOK, "user/login.html", gin.H{})
			}
			//fmt.Println(token)
			ctx.SetCookie("username", user.Username, 60*60*24, "/", "", false, true)
			ctx.SetCookie("token", token, 60*60*24, "/", "", false, true)
			// 返回登录后的页面
			ctx.HTML(http.StatusOK, "user/home.html", gin.H{
				"username": user.Username,
				"token":    token,
			})
			return
			//	gin.H{
			//	"status":   code,
			//	"token":    token,
			//	"username": user.Username,
			//},

		} else {
			ctx.String(http.StatusOK, "用户验证错误")
			// 返回错误页面
			//ctx.JSON(http.StatusOK, gin.H{
			//	"status":  code,
			//	"data":    user.Username,
			//	"id":      user.ID,
			//	"message": errmsg.GetErrMsg(code),
			//	"token":   token,
			//})
			return
		}
	}
	if ctx.Request.Method == "GET" {
		ctx.HTML(http.StatusOK, "user/login.html", gin.H{})
	}

}

// 生成token 1.0 前后端不分离的
func CreateToken(ctx *gin.Context, user model.User) (token string, err error) {
	j := middeware.NewJWT()
	claims := middeware.MyClaims{
		Username: user.Username,
		RegisteredClaims: jwt.RegisteredClaims{
			NotBefore: jwt.NewNumericDate(time.Now()),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)),
			Issuer:    "ginBlog",
		},
	}
	token, err = j.CreateToken(claims)
	if err != nil {
		return "", err
	}
	return token, nil
}

func Home(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "user/home.html", gin.H{
		"title":   "Home",
		"message": "success",
	})
}
